package leetcode.code0611;

import java.util.Arrays;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int triangleNumber(int[] nums) {
		Arrays.sort(nums);
		int ans = 0;
		for (int i = 2; i < nums.length; i++) {
			int c = nums[i];
			for (int j = i - 1; j > 0; j--) {
				// 在nums上[0,j]范围内大于c - nums[j] 的数量
				ans += this.search(nums, j, c - nums[j]);
			}
		}
		return ans;
	}

	private int search(int[] nums, int right, int range) {
		int l = 0, r = right - 1;
		int index = -1;
		while (l <= r) {
			int m = ((r - l) >> 1) + l;
			if (nums[m] > range) {
				index = m;
				r = m - 1;
			} else {
				l = m + 1;
			}
		}
		return index == -1 ? 0 : right - index;
	}

	@Override
	public void debug4() {
		H.compare(3, this.triangleNumber(H.str2array3("[2,2,3,4]")));
		H.compare(209, this.triangleNumber(H.str2array3("[2,2,3,4,1,2,3,4,5,6,7,22,3,3,3,99,67,22]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
